<?php
	/**
	 * Created by PhpStorm.
	 * User: mybook-lhp
	 * Date: 18/5/8
	 * Time: 下午1:30
	 */


	namespace app\store\api;


	use app\store\model\StoreOrder;
	use think\Controller;
	use think\Db;
	use think\Log;

	class Callback extends Controller
	{
		/**
		 * 解析xml
		 * @return array
		 */
		public function analysis_xml()
		{
			$res_xml = file_get_contents("php://input");
			libxml_disable_entity_loader(true);
			$postObj = simplexml_load_string($res_xml, 'SimpleXMLElement', LIBXML_NOCDATA);

			return ['array' => json_decode(json_encode($postObj), true), 'xml' => $res_xml];
		}

		/**
		 * 微信回调
		 * @throws \think\Exception
		 * @throws \think\exception\PDOException
		 */
		public function wechatpay()
		{
			Log::info(time() . '微信来了');
			$wx_data = $this->analysis_xml();

			$log['pay_type'] = 'weixin';
			$log['original'] = $wx_data['xml'];
			$log['log_content'] = json_encode($wx_data['array']);
			$log['create_time'] = time();
			Db::name('paymentlog')->insert($log);
			Log::info(json_encode($log));

			if ($wx_data['array']['return_code'] == 'SUCCESS' && $wx_data['array']['result_code'] == 'SUCCESS')
			{
				$data = array();
				$data['pay_sn'] = $wx_data['array']['out_trade_no'];
				$data['pay_type'] = 'weixin';
				$data['trade_no'] = $wx_data['array']['transaction_id'];
				$data['total_fee'] = $wx_data['array']['total_fee'];
				$data['time_end'] = $wx_data['array']['time_end'];
				$data['appid'] = $wx_data['array']['appid'];
				$result = StoreOrder::update(['order_status' => 20], ['pay_sn' => $data['pay_sn']]);
				if ($result)
				{
					$xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg>";
					$xml .= "</xml>";
					echo $xml;
				} else
				{
					Log::info(json_encode(json_encode($result)));
					echo 'fail';
				}
			}
			Log::info(time() . '微信走了');
		}


		public function alipay()
		{
			$params = $this->request->param();
			Log::info('支付宝回调成功！:' . json_encode($params));
		}


	}